
import { Menu } from 'antd'
import {
  DesktopOutlined,
  FileOutlined,
  PieChartOutlined,
  TeamOutlined,
  UserOutlined,
} from '@ant-design/icons';
import { useState } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import { ItemType } from 'antd/lib/menu/hooks/useItems';

const menuItems: ItemType[] = [
  {
    label: 'Option 1',
    key: '/page1',
    icon: <PieChartOutlined />,
  },
  {
    label: 'Option 2',
    key: '/page2',
    icon: <DesktopOutlined />,
  },
  {
    label: 'Option 3',
    key: '/page3',
    icon: <UserOutlined />,
    children: [
      {
        label: 'Option 3 - 1',
        key: '/page3/p1',
      },
      {
        label: 'Option 3 - 2',
        key: '/page3/p2',
      },
      {
        label: 'Option 3 - 3',
        key: '/page3/p3',
      },
    ]
  },
  {
    label: 'Option 4',
    key: '/page4',
    icon: <TeamOutlined />,
    children: [
      {
        label: 'Option 4 - 1',
        key: '/page4/p1',
      },
      {
        label: 'Option 4 - 2',
        key: '/page4/p2',
      }
    ]
  },
  {
    label: 'Option 5',
    key: '/page5',
    icon: <FileOutlined />,
  },
]

const View = function () {
  const currentKey = useLocation();
  const navigateTo = useNavigate();

  let firstKey: string = '';
  menuItems.some((item: any) => {
    if (item.children && item.children.length > 0) {
      if (item.children.find((i: any) => i.key === currentKey.pathname)) {
        firstKey = item.key as string;
        return true
      }
    }
  });

  const [menuOpenKeys, setMenuOpenKeys]: any[] = useState([firstKey]);

  const menuClick = (e: { key: string }) => {
    navigateTo(e.key);
  };
  const handleOpenChange = (openKey: string[]) => setMenuOpenKeys([openKey[openKey.length - 1]])
  return <Menu
    theme="dark"
    defaultSelectedKeys={[currentKey.pathname]}
    mode="inline"
    items={menuItems}
    onClick={menuClick}
    onOpenChange={handleOpenChange}
    openKeys={menuOpenKeys}
  />
}

export default View;